
from atm.core import db_handle, logger
from atm.conf import setting

class Account:

    __slots__ = ["account", "password", "card_limit", "balance", "is_freeze"]

    def __init__(self):
        self.account = None
        self.password = None
        self.card_limit = None
        self.balance = None
        self.is_freeze = None

    def get_all_attr(self) -> dict:
        attr_dict = {}
        for value in self.__slots__:
            try:
                attr_dict[value] = getattr(self, value)
            except Exception:
                raise ValueError("%s can't be none" % value)
        return attr_dict

    def create(self):
        db_handle.create_account(**self.get_all_attr())

    def read(self):
        user_dict = db_handle.read_account(account=self.account)
        for value in self.__slots__:
            setattr(self, value, user_dict[value])

    def edit(self):
        db_handle.edit_account(**self.get_all_attr())

    def delete(self):
        db_handle.del_account(self.account)

    # 提现
    def withdraw_deposit(self, money: float):
        temp_balance = self.balance - money * (1 + setting.SERVICE_CHARGE)
        if temp_balance < 0:
            raise ValueError("您的余额不足")
        else:
            self.balance = temp_balance
            self.edit()
        logger.atm_log("提现%.2f元" % money, 1)

    # 转账
    def transfer_account(self, money: float, account: str):
        after_change_balance = self.balance - money
        minus_success = False
        add_success = False
        if after_change_balance < 0:
            raise ValueError("您的余额不足")
        else:
            self.balance = after_change_balance
            other_account_dict = db_handle.read_account(account)
            other_account_dict["balance"] += money
            try:
                db_handle.edit_account(**other_account_dict)
                add_success = True
                self.edit()
                minus_success = True

            except Exception:
                print("转账失败")
            else:
                logger.atm_log("转账给 %s %.2f元" % (account, money), 1)
                return None
        if not add_success or not minus_success:
            other_account_dict = db_handle.read_account(account)
            other_account_dict["balance"] -= money
            self.balance += money


    # 消费
    def expend(self, money: float, good_name: str=None):
        temp_balance = self.balance - money
        if temp_balance <= 0:
            raise ValueError("您的余额不足")
        else:
            self.balance = temp_balance
            self.edit()
            logger.atm_log("购买了 %s, 消费了%.2f元" % (good_name if good_name else "", money), 1)

    def repay(self, money: float):
        need_reply_money = self.card_limit - self.balance
        if 0 < money <= need_reply_money:
            self.balance += money
            self.edit()
            logger.atm_log("还款%.2f元" % money, 1)


if __name__ == "__main__":
    pass
